package com.ywu.application.standard.container.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.google.gson.internal.LinkedTreeMap;
import com.ywu.application.standard.service.api.ServiceApi;
import com.ywu.application.standard.service.dto.ServiceDto;
import com.ywu.application.standard.service.entity.ServiceEntity;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.mapper.YwuBeanMapper;
import com.ywu.common.result.CommonResult;
import com.ywu.application.standard.container.config.YwuContainerAppConfig;
import com.ywu.application.standard.container.data.ServiceContainerRepository;
import com.ywu.application.standard.container.dto.ContainerCmdDto;
import com.ywu.application.standard.container.dto.ContainerLogDto;
import com.ywu.application.standard.container.dto.ServiceContainerDto;
import com.ywu.application.standard.container.entity.PipeLineRedisEntity;
import com.ywu.application.standard.container.entity.ServiceContainerEntity;
import com.ywu.application.standard.container.entity.SshConfigEntity;
import com.ywu.application.standard.container.entity.step.StepEntity;
import com.ywu.application.standard.container.entity.step.StepStatus;
import com.ywu.application.standard.container.util.DockerClientUtils;
import com.ywu.application.standard.container.util.SSHUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @ClassName ServiceContainerService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/3/4 21:17
 * @Version 1.0
 **/
@Service
public class ServiceContainerService {
    private final static Logger log = LoggerFactory.getLogger(ServiceContainerService.class);

    @Autowired
    private DockerClientUtils dockerClientUtils;

    @Autowired
    private ServiceContainerRepository serviceContainerRepository;

    @Autowired
    private ServiceApi serviceApi;

    @Autowired
    private PipeLineRedisService pipeLineRedisService;

    @Autowired
    private YwuContainerAppConfig ywuContainerAppConfig;

    private static final String MAVEN_FAIL_FLAG_STR = "[INFO] BUILD FAILURE";

    /**
    * @Author GroundDemo
    * @Description 创建容器
    * @Date 21:20 2024/3/4
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> createContainer(ServiceContainerDto serviceContainerDto) {
        // 创建容器
        CreateContainerResponse container = dockerClientUtils.createContainers(serviceContainerDto);
        // 设置容器的ID
        serviceContainerDto.setDockerContainerId(container.getId());
        // 插入数据
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        serviceContainerEntity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        serviceContainerEntity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        serviceContainerRepository.addContainerInfo(serviceContainerEntity);
        return CommonResult.success(null);
    }

    /**
     * @Author GroundDemo
     * @Description 构建项目
     * @Date 20:11 2024/3/6
     * @Param [serviceContainerDto]
     * @return void
     **/
    @Async
    public void buildContainer(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        serviceContainerEntity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        if (Objects.isNull(resEntity)) {
            log.error("buildContainer container is not exist!!!");
            throw new YwuRuntimeException("buildContainer container is not exist");
        }
        // 根据容器绑定的微服务ID查询微服务相关信息
        CommonResult<Object> serviceEntityRes = getServiceEntity(resEntity);
        if (Objects.isNull(serviceEntityRes) || !StringUtils.equals(serviceEntityRes.getCode(), "200")) {
            log.error("buildContainer getServiceEntity error {}", serviceEntityRes.getErrorCode());
            return;
        }
        ServiceEntity serviceEntity = (ServiceEntity) serviceEntityRes.getData();
        // 构建执行命令
        // 1、拉取代码仓
        String command = pullGitInfo(resEntity, serviceEntity);
        // 2、mvn构建代码
        mvnBuildInfo(resEntity, serviceEntity, "source /root/.bashrc;");
    }

    /**
    * @Author GroundDemo
    * @Description 推包至容器的挂载目录
    * @Date 20:22 2024/3/6
    * @Param []
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Async
    public void pushPackage(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        serviceContainerEntity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        if (Objects.isNull(resEntity)) {
            log.error("pushPackage container is not exist!!!");
            throw new YwuRuntimeException("pushPackage container is not exist");
        }
        // 根据容器绑定的微服务ID查询微服务相关信息
        CommonResult<Object> serviceEntityRes = getServiceEntity(resEntity);
        if (Objects.isNull(serviceEntityRes) || !StringUtils.equals(serviceEntityRes.getCode(), "200")) {
            log.error("pushPackage getServiceEntity error {}", serviceEntityRes.getErrorCode());
            return;
        }
        ServiceEntity serviceEntity = (ServiceEntity) serviceEntityRes.getData();
        pushPackageInfo(serviceEntity, resEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 部署容器
    * @Date 19:49 2024/3/5
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Async
    public void deployContainer(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        serviceContainerEntity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        if (Objects.isNull(resEntity)) {
            log.error("deployContainer container is not exist!!!");
            throw new YwuRuntimeException("deployContainer container is not exist");
        }
        StepEntity stepEntity = new StepEntity();
        // 记录命令执行时间
        String startTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setStartTime(startTime);
        stepEntity.setDockerName(resEntity.getDockerName());
        pipeLineRedisService.buildDeployContainer(stepEntity, resEntity.getDockerContainerId(), false);
        try {
            dockerClientUtils.restartContainer(resEntity);
        } catch (Exception e) {
            stepEntity.setPipeLineStatus(StepStatus.ERROR);
            stepEntity.setPipeLineResStr(e.toString());
            log.error("docker restart container error {}", e.getMessage());
        }
        String endTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setEndTime(endTime);
        // 构建step的对象并存储进入redis
        pipeLineRedisService.buildDeployContainer(stepEntity, resEntity.getDockerContainerId(), true);
    }

    /**
    * @Author GroundDemo
    * @Description 根据容器绑定的微服务ID查询微服务相关信息
    * @Date 20:18 2024/3/6
    * @Param [resEntity]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    private CommonResult<Object> getServiceEntity(ServiceContainerEntity resEntity) {
        ServiceDto serviceDto = new ServiceDto();
        serviceDto.setId(resEntity.getServiceId());
        CommonResult<Object> allApplication = serviceApi.getAllApplication(serviceDto);
        if (Objects.isNull(allApplication) || !StringUtils.equals(allApplication.getCode(), "200")) {
            log.error("query service error");
            return allApplication;
        }
        String serialize = GsonUtils.serialize(allApplication.getData());
        List<LinkedTreeMap<String, Object>> deserialize = GsonUtils.deserialize(serialize, List.class);
        if (CollectionUtils.isEmpty(deserialize)) {
            log.error("can not relate to any service");
            return CommonResult.error().setMessage("can not relate to any service");
        }
        LinkedTreeMap<String, Object> serviceMap = deserialize.get(0);
        log.debug("getServiceEntity serviceEntity {}", serviceMap);
        ServiceEntity serviceEntity = YwuBeanMapper.map(serviceMap, ServiceEntity.class);
        log.debug("getServiceEntity serviceEntity {}", serviceEntity.toString());
        return CommonResult.success(serviceEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 重启容器
    * @Date 21:19 2024/3/6
    * @Param [serviceContainerDto]
    * @return void
    **/
    @Async
    public void restartContainer(List<ServiceContainerDto> serviceContainerDtos, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        String tenantId = currentContext.getYwuContextTenant().getTenantId();
        for (ServiceContainerDto serviceContainerDto : serviceContainerDtos) {
            serviceContainerDto.setTenantId(tenantId);
            ServiceContainerEntity checkRes = serviceContainerRepository.checkContainerInfo(serviceContainerDto);
            if (Objects.isNull(checkRes) || Objects.isNull(checkRes.getId())) {
                log.error("restartContainer container is not exist");
                throw new YwuRuntimeException("restartContainer container is not exist");
            }
            ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
            BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
            // 根据条件查询容器详情
            ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
            try {
                dockerClientUtils.restartContainer(resEntity);
            } catch (Exception e) {
                log.error("restart container error {}", e.getMessage());
                throw new YwuRuntimeException("restart container error");
            }
        }
    }

    /**
    * @Author GroundDemo
    * @Description 删除容器
    * @Date 21:28 2024/3/6
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Async
    public void deleteContainer(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        serviceContainerDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        ServiceContainerEntity checkRes = serviceContainerRepository.checkContainerInfo(serviceContainerDto);
        if (Objects.isNull(checkRes) || Objects.isNull(checkRes.getId())) {
            log.error("deleteContainer container is not exist");
            throw new YwuRuntimeException("deleteContainer container is not exist");
        }
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        dockerClientUtils.stopContainer(resEntity);
        dockerClientUtils.removeContainer(resEntity);
        // 删除数据
        serviceContainerRepository.deleteContainerInfo(resEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 更新容器
    * @Date 21:35 2024/3/6
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Async
    public void updateContainer(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        serviceContainerDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        ServiceContainerEntity checkRes = serviceContainerRepository.checkContainerInfo(serviceContainerDto);
        if (Objects.isNull(checkRes) || Objects.isNull(checkRes.getId())) {
            log.error("updateContainer container is not exist");
            throw new YwuRuntimeException("updateContainer container is not exist");
        }
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        serviceContainerEntity.setId(serviceContainerDto.getId());
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        // 先停用和删除当前容器
        dockerClientUtils.stopContainer(resEntity);
        dockerClientUtils.removeContainer(resEntity);
        // 创建容器
        CreateContainerResponse container = dockerClientUtils.createContainers(serviceContainerDto);
        // 设置容器的ID
        serviceContainerDto.setDockerContainerId(container.getId());
        // 更新数据库数据
        ServiceContainerEntity updateContainerDto = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, updateContainerDto);
        updateContainerDto.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        serviceContainerRepository.updateContainerInfo(updateContainerDto);
    }

    /**
    * @Author GroundDemo
    * @Description 一键部署容器
    * @Date 21:45 2024/3/6
    * @Param [serviceContainerDto]
    * @return void
    **/
    @Async
    public void simpleDeployContainer(ServiceContainerDto serviceContainerDto, YwuContext currentContext) {
        YwuContextHolder.setCurrentContext(currentContext);
        // 构建项目
        this.buildContainer(serviceContainerDto, currentContext);
        // 推包
        this.pushPackage(serviceContainerDto, currentContext);
        // 部署
        this.deployContainer(serviceContainerDto, currentContext);
    }

    /**
    * @Author GroundDemo
    * @Description 查询容器
    * @Date 22:12 2024/3/6
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryContainer(ServiceContainerDto serviceContainerDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        serviceContainerDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        List<ServiceContainerEntity> entityList = serviceContainerRepository.queryContainerList(serviceContainerEntity);
        entityList.forEach(res -> {
            res.setCmdList(GsonUtils.deserializeList(res.getDockerCmdListStr(), ContainerCmdDto.class));
        });
        return CommonResult.success(entityList);
    }

    /**
    * @Author GroundDemo
    * @Description 查询容器的日志
    * @Date 0:20 2024/3/9
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> containerInfoLogs(ServiceContainerDto serviceContainerDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        serviceContainerDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        // 根据条件查询容器详情
        ServiceContainerEntity resEntity = serviceContainerRepository.queryContainer(serviceContainerEntity);
        if (Objects.isNull(resEntity)) {
            log.error("containerInfoLogs container is not exist");
            return CommonResult.error().setMessage("container is not exist");
        }
        List<String> containerLogs = dockerClientUtils.getContainerLogs(resEntity, serviceContainerDto.getBeginTimestamp(), serviceContainerDto.getEndTimestamp());
        return CommonResult.success(containerLogs);
    }

    /**
    * @Author GroundDemo
    * @Description 拉取git代码仓
    * @Date 15:22 2024/4/13
    * @Param [resEntity, serviceEntity]
    * @return java.lang.String
    **/
    private String pullGitInfo(ServiceContainerEntity resEntity, ServiceEntity serviceEntity) {
        // 记录流水线信息
        StepEntity stepEntity = new StepEntity();
        String command = "rm -rf " + resEntity.getDockerGitPath() + ";";  // 删除目标目录
        command += "mkdir -p " + resEntity.getDockerGitPath() + ";";  // 创建目标目录
        command += "cd " + resEntity.getDockerGitPath() + ";"; // 切换当前目录
        command += "git clone " + serviceEntity.getGitPath() + ";"; // 克隆git项目
        // 执行git clone构建
        // 记录命令执行时间
        String startTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setStartTime(startTime);
        stepEntity.setGitPath(serviceEntity.getGitPath());
        pipeLineRedisService.buildPullGitRedisInfo(stepEntity, resEntity.getDockerContainerId());
        log.debug("git pull info command is {}", command);
        try {
            String execRes = SSHUtils.execCommand(ywuContainerAppConfig.getSshHost(), ywuContainerAppConfig.getSshPort(),
                    ywuContainerAppConfig.getSshUserName(), ywuContainerAppConfig.getSshPassword(), command);
            stepEntity.setPipeLineStatus(StepStatus.SUCCESS);
            stepEntity.setPipeLineResStr(execRes);
        } catch (Exception e) {
            stepEntity.setPipeLineStatus(StepStatus.ERROR);
            stepEntity.setPipeLineResStr(e.toString());
            log.error("git pull error {}", e.getMessage());
        }
        String endTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setEndTime(endTime);
        // 构建step的对象并存储进入redis
        pipeLineRedisService.buildPullGitRedisInfo(stepEntity, resEntity.getDockerContainerId());
        return command;
    }

    /**
    * @Author GroundDemo
    * @Description maven构建jar包
    * @Date 15:22 2024/4/13
    * @Param [resEntity, serviceEntity, command]
    * @return void
    **/
    private void mvnBuildInfo(ServiceContainerEntity resEntity, ServiceEntity serviceEntity, String command) {
        // 记录流水线信息
        StepEntity stepEntity = new StepEntity();
        String dockerGitPath = resEntity.getDockerGitPath();
        if (!dockerGitPath.endsWith("/")) {
            dockerGitPath += "/";
        }
        command += "cd " + dockerGitPath + serviceEntity.getPomPath() + ";"; // 切换至pom文件目录
        command += ywuContainerAppConfig.getMavenPath() + " clean; " + ywuContainerAppConfig.getMavenPath() + " install;"; // maven构建项目
        // 记录命令执行时间
        String startTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setStartTime(startTime);
        stepEntity.setPomPath(serviceEntity.getPomPath());
        pipeLineRedisService.buildMvnBuildInfo(stepEntity, resEntity.getDockerContainerId(), false);
        // 执行maven构建
        try {
            String execRes = SSHUtils.execCommand(ywuContainerAppConfig.getSshHost(), ywuContainerAppConfig.getSshPort(),
                    ywuContainerAppConfig.getSshUserName(), ywuContainerAppConfig.getSshPassword(), command);
            stepEntity.setPipeLineResStr(execRes);
            // 判断当前maven是否构建成功
            String[] split = execRes.split("\n");
            for (String s : split) {
                if (s.startsWith(MAVEN_FAIL_FLAG_STR)) {
                    stepEntity.setPipeLineStatus(StepStatus.ERROR);
                    log.error("mvn build error");
                }
            }
        } catch (Exception e) {
            stepEntity.setPipeLineStatus(StepStatus.ERROR);
            stepEntity.setPipeLineResStr(e.toString());
            log.error("mvn build error {}", e.getMessage());
        }
        String endTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setEndTime(endTime);
        // 构建step的对象并存储进入redis
        pipeLineRedisService.buildMvnBuildInfo(stepEntity, resEntity.getDockerContainerId(), true);
    }

    /**
     * @Author GroundDemo
     * @Description 构建完之后推包至挂载路径
     * @Date 15:22 2024/4/13
     * @Param [resEntity, serviceEntity, command]
     * @return void
     **/
    private void pushPackageInfo(ServiceEntity serviceEntity, ServiceContainerEntity resEntity) {
        // 记录流水线信息
        StepEntity stepEntity = new StepEntity();
        String dockerGitPath = resEntity.getDockerGitPath();
        if (!dockerGitPath.endsWith("/")) {
            dockerGitPath += "/";
        }
        // 记录命令执行时间
        String startTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setStartTime(startTime);
        stepEntity.setPushJarName(serviceEntity.getJarName());
        pipeLineRedisService.buildPushPackageInfo(stepEntity, resEntity.getDockerContainerId(), false);
        // 拷贝包至挂载路径
        SshConfigEntity sshConfig = ywuContainerAppConfig.getSshConfig(resEntity.getDockerServiceAddress());
        if (Objects.isNull(sshConfig)) {
            throw new YwuRuntimeException("ip ssh config not exist");
        }
        try {
            // 先下载到本地，在上传至远程服务
            String temp = dockerGitPath + serviceEntity.getJarPath();
            int index = temp.lastIndexOf("/");
            String jarPath = temp.substring(0, index);
            String jarName = temp.substring(index + 1);
            SSHUtils.downloadFile(ywuContainerAppConfig.getSshHost(), ywuContainerAppConfig.getSshPort(), ywuContainerAppConfig.getSshUserName(), ywuContainerAppConfig.getSshPassword(),
                    jarPath, jarName, ywuContainerAppConfig.getJarLocalFilePath(), jarName);
            log.debug("jar file download finish");
            SSHUtils.uploadFile(sshConfig.getSshHost(), Integer.parseInt(sshConfig.getSshPort()), sshConfig.getSshUser(), sshConfig.getSshPassword(),
                    ywuContainerAppConfig.getDockerJarPath(), serviceEntity.getJarName(), ywuContainerAppConfig.getJarLocalFilePath(), jarName);
            log.debug("jar file upload finish");
            stepEntity.setPipeLineStatus(StepStatus.SUCCESS);
            stepEntity.setPipeLineResStr("");
        } catch (Exception e) {
            stepEntity.setPipeLineStatus(StepStatus.ERROR);
            stepEntity.setPipeLineResStr(e.toString());
            log.error("push file error {}", e.getMessage());
        }
        String endTime = pipeLineRedisService.getCurrentTime();
        stepEntity.setEndTime(endTime);
        // 构建step的对象并存储进入redis
        pipeLineRedisService.buildPushPackageInfo(stepEntity, resEntity.getDockerContainerId(), true);
    }

    /**
    * @Author GroundDemo
    * @Description 查询流水线步骤信息
    * @Date 23:11 2024/4/13
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryStepInfo(ServiceContainerDto serviceContainerDto) {
        PipeLineRedisEntity redisEntity = pipeLineRedisService.getRedisEntity(serviceContainerDto.getDockerContainerId());
        return CommonResult.success(redisEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 根据containerId批量查询容器详情
    * @Date 20:22 2024/5/22
    * @Param [containerIds]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> containerDetailsQuery(ServiceContainerDto serviceContainerDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        serviceContainerDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        ServiceContainerEntity serviceContainerEntity = new ServiceContainerEntity();
        BeanUtils.copyProperties(serviceContainerDto, serviceContainerEntity);
        List<ServiceContainerEntity> entityList = serviceContainerRepository.queryContainerList(serviceContainerEntity);
        List<ServiceContainerDto> serviceContainerDtos = new ArrayList<>();
        dockerClientUtils.queryContainerDetails(entityList, serviceContainerDtos);
        return CommonResult.success(serviceContainerDtos);
    }

    /**
    * @Author GroundDemo
    * @Description 查询容器的日志文件列表 - 只展示名称和文件大小
    * @Date 10:08 2025/3/26
    * @Param [serviceContainerDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryContainerAppLogList(ServiceContainerDto serviceContainerDto) {
        // 根据当前容器ID和租户ID查询当前容器信息
        ServiceContainerEntity search = new ServiceContainerEntity();
        search.setDockerContainerId(serviceContainerDto.getDockerContainerId());
        search.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        ServiceContainerEntity queryEntity = serviceContainerRepository.queryContainer(search);
        if (Objects.isNull(queryEntity)) {
            log.error("queryContainerAppLogList container is not exist");
            return CommonResult.error().setMessage("queryContainerAppLogList container is not exist");
        }
        // 查询日志文件列表
        List<ContainerLogDto> logDtoList = dockerClientUtils.queryAppLogList(queryEntity);
        return CommonResult.success(logDtoList);
    }

    /**
    * @Author GroundDemo
    * @Description 下载应用日志
    * @Date 12:16 2025/3/26
    * @Param [containerLogDto, response]
    * @return void
    **/
    public void downloadAppLog(ContainerLogDto containerLogDto, HttpServletResponse response) {
        // 根据容器ID查询容器信息
        ServiceContainerEntity search = new ServiceContainerEntity();
        search.setDockerContainerId(containerLogDto.getContainerId());
        search.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        ServiceContainerEntity queryEntity = serviceContainerRepository.queryContainer(search);
        if (Objects.isNull(queryEntity)) {
            log.error("downloadAppLog container is not exist");
            throw new YwuRuntimeException("downloadAppLog container is not exist");
        }
        SshConfigEntity sshConfig = ywuContainerAppConfig.getSshConfig(queryEntity.getDockerServiceAddress());
        if (Objects.isNull(sshConfig)) {
            throw new YwuRuntimeException("ip ssh config not exist");
        }
        // 去对应容器下载文件
        dockerClientUtils.downLoadFileResponse(queryEntity, ywuContainerAppConfig.getAppLogPath(), containerLogDto.getLogFileName(),
                response);
    }
}
